//  admin router
module.exports = (app) => {
  const express = require('express');
  const jwt = require('jsonwebtoken');
  const AdminUser = require('../../models/Adminuser');
  const assert = require('http-assert');
  const router = express.Router({
    // mergeParams: true,
  }); //子路由
  // const Category = require('../../models/Category');

  // 登陆校验中间件 对 token进行校验
  const authMiddlware = require('../../middleware/auth');

  //  资源中间件 根据路由转换匹配模型
  const resourceMideleware = require('../../middleware/resource');

  //   获取全部分类
  router.get('/', async (req, res) => {
    //  这里要查询关联 所以对要进行关联查询的开放
    const queryOptions = {};
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent';
    }
    let data = await req.Model.find().setOptions(queryOptions).limit(100);
    res.send(data);
  });

  //   获取某个分类
  router.get('/:id', async (req, res) => {
    let data = await req.Model.findById(req.params.id);
    res.send(data);
  });

  //   添加分类
  router.post('/', async (req, res) => {
    let data = await req.Model.create(req.body);
    res.send(data);
  });

  //   修改
  router.put('/:id', async (req, res) => {
    let data = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send(data);
  });

  //   删除分类
  router.delete('/:id', async (req, res) => {
    let data = await req.Model.findByIdAndDelete(req.params.id);
    res.send(data);
  });

  app.use('/admin/api/rest/:resource', authMiddlware(), resourceMideleware(), router);

  // 图片上传
  const multer = require('multer');
  const upload = multer({ dest: __dirname + '/../../upload' });
  app.post('/admin/api/upload', authMiddlware(), upload.single('file'), async (req, res) => {
    const file = req.file;
    file.url = `http://localhost:3000/upload/${file.filename}`;
    res.send(file);
  });

  /**
   * 用户登录
   * 1.根据用户名找用户
   * 2.校验密码
   * 3.返回token
   */
  app.post('/admin/api/login', async (req, res) => {
    const { username, password } = req.body;

    const user = await AdminUser.findOne({ username }).select('+password');
    assert(user, 422, '用户不存在');
    const isValid = require('bcrypt').compareSync(password, user.password);
    assert(isValid, 422, '密码错误');
    // token
    const token = jwt.sign({ id: user._id }, app.get('secret'));
    res.send({ token, username });
  });

  // 错误处理函数
  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
      message: err.message,
    });
  });
};
